import axios from 'axios'
import Qs from 'qs'
// 时间戳
// const NewTimeStamp = new Date().getTime()
// 定义请求类
class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
    }
    return config
  }
  // 小程序自定义处理请求
  adapter (instance) {
    instance.defaults.timeout = 30000
    instance.defaults.adapter = function (config) {
      return new Promise((resolve, reject) => {
        // console.log(config,'adapter')
        let data = config.method === 'get' ? config.params : Qs.stringify(Object.assign(JSON.parse(config.data),vertifyData()))
        // wx小程序 发起请求相应 log 就可以看到熟悉的返回啦
        // console.log(typeof config.data, config, data)
        wx.request({
          url: config.url,
          method: config.method,
          data: data,
          header: {
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' // 默认值
          },
          success: (res) => {
            return resolve(res.data)
          },
          fail: (err) => { return reject(err) }
        })
      })
    }
  }
  distroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  // 拦截器
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      // 统一拦截添加token
      config.params = {}
      // config.params.token = getToken()
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.distroy(url)
      const { data, status } = res
      // 接口token过期处理
      // if (res.data.Code === -202) {
      //   router.push({ name: 'login', params: { failure: true } })
      //   // return Promise.reject(new Error(res.data.Message).message)
      // }
      return { data, status }
    }, error => {
      this.distroy(url)
      return Promise.reject(error)
    })
  }
  // 请求开始
  request (options) {
    const instance = axios.create()
    const configInfo = this.getInsideConfig()
    this.adapter(instance)
    options.url = this.getInsideConfig().baseURL + options.url
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
